package com.fudan.backend.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Component
public class StringUtil {

    @Autowired
    private ObjectMapper MAPPER;

    /**
     * 将List转为json格式
     * @param object 输入对象
     * @return json格式的字符串
     */
    public String toJson(List<String> object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将json解为list
     * @param content json字符串
     * @return 包含的内容链表
     */
    public List<String> toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                return (List<String>) MAPPER.readValue(content, (Class<?>) List.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }

    /**
     * 验证邮箱格式
     * @return 返回是否符合
     */
    public boolean checkEmailFomat(String email){
        if ((email != null) && (!email.isEmpty())) {
            return Pattern.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$", email);
        }
        return false;
    }

    /**
     * 验证大陆手机号码格式
     * @param phoneNumber 手机号码
     * @return 返回是否符合格式
     */
    public boolean checkPhoneNumberFormat(String phoneNumber){
        if ((phoneNumber != null) && (!phoneNumber.isEmpty())) {
            return Pattern.matches("^((13[0-9])|(15[0-9])|(18[0-9]))\\d{8}$", phoneNumber);
        }
        return false;
    }

    /**
     *验证身份证号格式
     */
    public boolean checkIdCardNumberFormat(String id){
        if ((id != null) && (!id.isEmpty())) {
            return Pattern.matches("^\\d{17}[0-9xX]$", id);
        }
        return false;
    }
    /**
     * 验证用户名格式
     */
    public boolean checkUserNameFormat(String username){
        if((username != null) && (!username.isEmpty())){
            return Pattern.matches("^\\w{3,10}$", username);
        }
        return false;
    }
    public List<String> objToList(Object obj){
        List<String> result = new ArrayList<String>();
        if(obj instanceof List<?>)
        {
            for (Object o : (List<?>) obj)
            {
                result.add(o.toString());
            }
            return result;
        }
        throw new RuntimeException();
    }

    /**
     * 判断list中的String内容是否均可转为Long型
     */
    public Boolean checkIdList(List<String> list){
        if(list.size() == 0){
            return false;
        }
        for(String id : list){
            if(!StringUtils.isNumeric(id))
                return false;
        }
        return true;
    }
}
